<?php

namespace app\site\controller\store;

use app\common\exception\MiException;
use app\common\service\pay\WxpayService;
use app\common\service\CommonSiteConfigService;
use app\Request;
use app\site\service\site\OrderService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;

class OrderController extends \app\site\controller\AController
{

    /**
     * @throws DbException
     */
    public function index(){
        $where = [];
        $key = $this->param('where.key');
        $orderStatus = $this->param('where.order_status', '');
        $createDate = $this->param('where.create_date');
        $uid = $this->param('where.user_id');
        if ($key){
            $where[] = ['id|order_no', '=', $key];
        }
        if ($orderStatus !== '') $where[] = ['order_status', '=', $orderStatus];
        if ($uid) $where[] = ['user_id', '=', $uid];
        if ($createDate) $where[] = ['create_time', 'BETWEEN TIME', $createDate];

        return $this->reqSer->setService(OrderService::instance()->setWhere($where))->setPaginate()->getResponse();
    }

    /**
     * 订单详情
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function edit(){
        return $this->reqSer->setService(OrderService::instance())->setFind()->getResponse();
    }

    /** 订单发货
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    public function delivery(): \think\response\Json
    {
        $post = $this->post();
        $order = OrderService::instance()->sendGoodsBySaleOrder(
            $post['order']['id'],
            $post['orderItems'] ?? [],
            $post['express_id'] ?? 0,
            $post['express_order_no'] ?? ''
        );
        // 查询最新的订单详情
        $lastOrder = OrderService::instance()->setPkWhere($order->id)->find();

        return jsonSuccess([
            'order' => $lastOrder
        ]);

    }

    // 取消订单
    public function cancel(Request $request): \think\response\Json
    {

        Db::transaction(function () use ($request) {
            $orderId = $request->param('order_id');
            $order = OrderService::instance()->setPkWhere($orderId)->find();
            if (!$order){
                throw new MiException("未查询到订单信息");
            }
            $orderStatus = $order->order_status;
            if (in_array($orderStatus, ['unpaid', 'paid', 'wait'])) {    // 可以取消的订单状态，如果订单已发货则只能申请售后。
                // 将订单状态改为关闭
                OrderService::instance()->close($order, 'cancel'); // 4 - 平台管理员取消订单
                if ($orderStatus!='unpaid'){
                    // 向买家全额退款（包含运费）
                    $config = CommonSiteConfigService::instance()->getWxPayConfig(SiteAuthService::instance()->getSiteId());
                    // 没有抛出异常，则退款成功
                    WxpayService::getInstance($config)->refunds([
                        'transaction_id' => $order->pay_order_no,
                        'out_refund_no'  => $order->order_no,
                        'amount'         => [
                            'refund'   => (int)$order->pay_price*100,
                            'total'    => (int)$order->pay_price*100,
                            'currency' => 'CNY',
                        ],
                    ]);


                }
            }
        });

        // 全程无异常
        return jsonSuccess();

    }


}
